package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.IntegrationRepository;
import cn.hd01.repository.entity.Customer;
import cn.hd01.repository.entity.Integration;
import cn.hd01.service.IntegrationService;

@Service
public class IntegrationServiceImpl extends BaseServiceImpl<Integration, Integer> implements IntegrationService {

	private IntegrationRepository repository;
	
	@Autowired
	public IntegrationServiceImpl(IntegrationRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public Page<Integration> findAll(final Integration integration, Pageable pageable) {
		if (integration == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<Integration>() {
			@Override
			public Predicate toPredicate(Root<Integration> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				Join<Integration, Customer> join = r.join("customer", JoinType.LEFT);
				
				
				if (StringUtils.hasText(integration.getCustomerName())) {
					predicates.add(cb.like(r.get("customerName").as(String.class), "%" + integration.getCustomerName() + "%"));
				}
				
				if(StringUtils.hasText(integration.getMobile())){
					predicates.add(cb.like(join.get("phoneNo").as(String.class), "%" + integration.getMobile() + "%"));
				}
				
				predicates.add(cb.equal(join.get("type").as(String.class), "0"));
				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
	}

	@Override
	public Integration findByCustomerId(Integer customerId) {
		return repository.findByCustomerId(customerId);
	}

	@Override
	public void deleteByCustomerId(Integer customerId) {
		repository.deleteByCustomerId(customerId);
	}

}
